package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.constant.Constant;
import com.csun.cmny.provider.dao.*;
import com.csun.cmny.provider.dto.ConfirmCycleBillDto;
import com.csun.cmny.provider.dto.OmcOldLeaveQueryDto;
import com.csun.cmny.provider.dto.OmcOldManBillDto;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.constant.OldInConstant;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.SendMessageRequest;
import com.csun.cmny.provider.model.dto.check_in.CheckInDaysDto;
import com.csun.cmny.provider.model.dto.cycle.CycleBillDto;
import com.csun.cmny.provider.model.dto.cycle.OldmanFixedQueryDto;
import com.csun.cmny.provider.model.dto.message.OldmanInQueryDto;
import com.csun.cmny.provider.model.dto.revise.GroupPaymentFeeQueryDto;
import com.csun.cmny.provider.model.vo.GroupVo;
import com.csun.cmny.provider.model.vo.OldmanRpcVo;
import com.csun.cmny.provider.model.vo.RpcRoleVo;
import com.csun.cmny.provider.model.vo.check_in.CheckInDaysVo;
import com.csun.cmny.provider.model.vo.cycle.OldmanBillVo;
import com.csun.cmny.provider.model.vo.old_out.OldOutVo;
import com.csun.cmny.provider.model.vo.revise.OldmanPaymentFeeVo;
import com.csun.cmny.provider.model.vo.revise.OldmanSetMealItemVo;
import com.csun.cmny.provider.model.vo.revise.OldmanSetMealVo;
import com.csun.cmny.provider.model.vo.revise.ReviseVo;
import com.csun.cmny.provider.pojo.Bed;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.pojo.OmcOldLeave;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.CronUtil;
import com.csun.cmny.provider.utils.DateUtil;
import com.csun.cmny.provider.vo.*;
import com.csun.cmny.util.PublicUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenzheng
 * @description:缴费记录单服务层
 * @date 2019/8/15 17:49
 */
@Order(value = 2)
@Slf4j
@Service
@Transactional
public class OmcOldManBillServiceImpl extends BaseService<OmcOldManBill> implements OmcOldManBillService {
    @Resource
    private OmcOldManBillMapper omcOldManBillMapper;
    @Resource
    private OmcBillAdjustFeeMapper omcBillAdjustFeeMapper;
    @Resource
    private OmcBillBackItemMapper omcBillBackItemMapper;
    @Resource
    private OmcBillInHospitalFeeMapper omcBillInHospitalFeeMapper;
    @Resource
    private OmcBillItemMapper omcBillItemMapper;
    @Resource
    private OmcBillMealMapper omcBillMealMapper;
    @Resource
    private OmcBillOutHospitalFeeMapper omcBillOutHospitalFeeMapper;
    @Resource
    private OmcBillPeriodFeeMapper omcBillPeriodFeeMapper;
    @Resource
    private OmcSetMealService omcSetMealService;
    @Resource
    private OmcReturnFeeConfigService returnFeeConfigService;
    @Resource
    private OldmanMapper oldmanMapper;
    @Resource
    private OmcCycleExpenseItemService cycleExpenseItemService;
    @Resource
    private OmcOldLeaveService oldLeaveService;
    @Resource
    private OmcPaymentCycleService paymentCycleService;
    @Resource
    private OmcOldManAccountFundsService accountFundsService;
    @Resource
    private OmcBillItemService omcBillItemService;
    @Resource
    private OmcOldManBillService omcOldManBillService;
    @Resource
    private OmcBillMealService omcBillMealService;
    @Resource
    private OmcBillInHospitalFeeService omcBillInHospitalFeeService;
    @Resource
    private OmcOldManSupplementMapper oldManSupplementMapper;
    @Resource
    private OmcBillSetMealItemService omcBillSetMealItemService;
    @Resource
    private OmcOldmanExpenseItemService omcOldmanExpenseItemService;
    @Resource
    private OmcOldManSupplementService omcOldManSupplementService;
    @Resource
    private OldmanService oldmanService;
    @Resource
    private UacRpcService uacRpcService;
    @Resource
    private BedService bedService;
    @Resource
    private OmcCycleExpenseItemMapper omcCycleExpenseItemMapper;
    @Resource
    private OmcOldOutService omcOldOutService;
    @Resource
    private OmcReviseService omcReviseService;
    @Resource
    private OpcMessageService opcMessageService;


    private LoginAuthDto loginAuthDto;

    @Override
    public List<OmcOldManBillVo> selectBillByName(OmcOldManBillDto omcOldManBillDto) {
        return omcOldManBillMapper.selectBillByName(omcOldManBillDto);
    }

    /**
     * 根据账单ID查询账单详情
     *
     * @param omcOldManBillDto
     * @return
     */
    @Override
    public OmcOldManBillDetailVo queryBillDetail(OmcOldManBillDto omcOldManBillDto) {
        OmcOldManBillDetailVo billDetailVo = omcOldManBillMapper.selectBillByKey(omcOldManBillDto);
        //根据账单类型填充账单详情
        if (null != billDetailVo) {//账单类型 1.入院账单 2.出院账单 3.调整账单 4.周期账单
            Long billId = omcOldManBillDto.getBillId();//账单ID
            Long groupId = omcOldManBillDto.getGroupId();
            if (billDetailVo.getBillType() == 1) {//入院账单
                //缴费项
                OmcBillItem omcBillItem = new OmcBillItem();
                omcBillItem.setBillId(billId);
                omcBillItem.setGroupId(groupId);
                billDetailVo.setBillItemList(omcBillItemMapper.select(omcBillItem));
                //选择的套餐
                OmcBillMeal omcBillMeal = new OmcBillMeal();
                omcBillMeal.setBillId(billId);
                omcBillMeal.setGroupId(groupId);
                omcBillMeal = omcBillMealMapper.selectOne(omcBillMeal);
                if (omcBillMeal != null) {
                    billDetailVo.setSetMealVo(omcSetMealService.getById(omcBillMeal.getSetMealId()));
                }
                //入院账单费用统计
                OmcBillInHospitalFee inHospitalFee = new OmcBillInHospitalFee();
                inHospitalFee.setBillId(billId);
                inHospitalFee.setGroupId(groupId);
                billDetailVo.setBillInHospitalFee(omcBillInHospitalFeeMapper.selectOne(inHospitalFee));
            } else if (billDetailVo.getBillType() == 2) {//出院账单
                //缴费项
                OmcBillItem omcBillItem = new OmcBillItem();
                omcBillItem.setBillId(billId);
                omcBillItem.setGroupId(groupId);
                billDetailVo.setBillItemList(omcBillItemMapper.select(omcBillItem));
                //退费项
                OmcBillBackItem backItem = new OmcBillBackItem();
                backItem.setBillId(billId);
                backItem.setGroupId(groupId);
                billDetailVo.setBillBackItemList(omcBillBackItemMapper.select(backItem));
                //出院账单费用统计
                OmcBillOutHospitalFee outHospitalFee = new OmcBillOutHospitalFee();
                outHospitalFee.setBillId(billId);
                outHospitalFee.setGroupId(groupId);
                billDetailVo.setBillOutHospitalFee(omcBillOutHospitalFeeMapper.selectOne(outHospitalFee));
            } else if (billDetailVo.getBillType() == 3) {//调整账单
                //调整前缴费项
                OmcBillItem omcBillItem = new OmcBillItem();
                omcBillItem.setBillId(billId);
                omcBillItem.setGroupId(groupId);
                omcBillItem.setAdjustOrder(1);
                billDetailVo.setBillItemBeforeList(omcBillItemMapper.select(omcBillItem));
                //调整后缴费项
                omcBillItem.setAdjustOrder(2);
                billDetailVo.setBillItemAfterList(omcBillItemMapper.select(omcBillItem));
                //调整账单费用统计
                OmcBillAdjustFee adjustFee = new OmcBillAdjustFee();
                adjustFee.setBillId(billId);
                adjustFee.setGroupId(groupId);
                billDetailVo.setBillAdjustFee(omcBillAdjustFeeMapper.selectOne(adjustFee));
            } else if (billDetailVo.getBillType() == 4) {//周期账单
                //缴费项
                OmcBillItem omcBillItem = new OmcBillItem();
                omcBillItem.setBillId(billId);
                omcBillItem.setGroupId(groupId);
                billDetailVo.setBillItemList(omcBillItemMapper.select(omcBillItem));
                //周期账单费用统计
                OmcBillPeriodFee periodFee = new OmcBillPeriodFee();
                periodFee.setBillId(billId);
                periodFee.setGroupId(groupId);
                billDetailVo.setBillPeriodFee(omcBillPeriodFeeMapper.selectOne(periodFee));
            }

        }
        return billDetailVo;
    }

    /**
     * 根据老人ID和账单类型查询账单详情
     *
     * @param omcOldManBillDto
     * @return
     */
    @Override
    public List<OmcOldManBillDetailVo> queryBillDetailList(OmcOldManBillDto omcOldManBillDto) {
        List<OmcOldManBillDetailVo> list = new ArrayList<>();
        OmcOldManBill dto = new OmcOldManBill();
        dto.setGroupId(omcOldManBillDto.getGroupId());
        if (omcOldManBillDto.getBillType() > 0) {
            dto.setBillType(omcOldManBillDto.getBillType());
        }
        dto.setOldManId(omcOldManBillDto.getOldManId());
        List<OmcOldManBill> dtoList = select(dto);
        if (null != dtoList && dtoList.size() > 0) {//查询每个账单的详情
            for (OmcOldManBill oldManBill : dtoList) {
                OmcOldManBillDto dto1 = new OmcOldManBillDto();
                dto1.setGroupId(omcOldManBillDto.getGroupId());
                dto1.setBillId(oldManBill.getId());
                OmcOldManBillDetailVo vo = queryBillDetail(dto1);
                if (null != vo) {
                    list.add(vo);
                }
            }
        }

        return list;
    }

    /**
     * 保存入院账单
     *
     * @param oldManBill        账单基础信息
     * @param billItemList      缴费项目信息
     * @param omcBillMeal       选择的套餐信息
     * @param billInHospitalFee 入院账单费用统计
     * @param loginAuthDto      登录人信息
     * @return
     */
    @Override
    public Integer saveInHospitalBill(OmcOldManBill oldManBill, List<OmcBillItem> billItemList, OmcBillMeal omcBillMeal, OmcBillInHospitalFee billInHospitalFee, LoginAuthDto loginAuthDto) {

        //判断是否已经生成了未缴费的入院账单
        if (checkOldmanInBillExist(oldManBill.getOldManId())) {

            //查询原有缴费单
            OmcOldManBill deleteBill = new OmcOldManBill();
            deleteBill.setOldManId(oldManBill.getOldManId());
            deleteBill.setBillType(1);
            deleteBill.setIsPay(0);
            deleteBill = selectOne(deleteBill);

            //定义账单id
            Long billId = deleteBill.getId();

            //删除原来的的账单数据
            //1.删除账单项目
            OmcBillItem billItemDel = new OmcBillItem();
            billItemDel.setBillId(billId);
            int retDelBillItem = omcBillItemService.delete(billItemDel);

            //2.删除绑定的套餐
            OmcBillMeal billMeal = new OmcBillMeal();
            billMeal.setBillId(billId);
            int retDelBillMeal = omcBillMealService.delete(billMeal);

            //3.删除绑定的套餐项目
            OmcBillSetMealItem billSetMealItem = new OmcBillSetMealItem();
            billSetMealItem.setBillId(billId);
            int retDelSetMealItem = omcBillSetMealItemService.delete(billSetMealItem);

            //4.删除账单绑定费用
            OmcBillInHospitalFee billInHospitalFeeDel = new OmcBillInHospitalFee();
            billInHospitalFeeDel.setBillId(billId);
            int retDelInHospitalFee = omcBillInHospitalFeeService.delete(billInHospitalFeeDel);

            //5.删除账单
            int retDeleteBill = deleteByKey(billId);
        }

        Oldman oldman = new Oldman();
        oldman.setOldmanId(oldManBill.getOldManId().intValue());
        Oldman old = oldmanService.selectByOld(oldman);



        Long groupId = loginAuthDto.getGroupId();
        oldManBill.setBillNumber(DateUtil.getPayNumber(groupId));//账单号
        oldManBill.setBillType(1);//账单类型 1.入院账单 2.出院账单 3.调整账单 4.周期账单
        oldManBill.setIsPay(0);
        oldManBill.setUpdateInfo(loginAuthDto);
        oldManBill.setGroupId(groupId);
        oldManBill.setOldManName(old.getOldName());

        int n = omcOldManBillMapper.insertSelective(oldManBill);//生成订单基础信息
        if (n > 0) {
            Long billId = oldManBill.getId();//账单ID
            //插入缴费项目信息
            if (null != billItemList && billItemList.size() > 0) {
                OmcBillItem billItemDto = new OmcBillItem();
                billItemDto.setGroupId(groupId);
                billItemDto.setBillId(billId);
//                if (omcBillItemMapper.selectCount(billItemDto) > 0) {//该账单已有缴费项目记录删除,避免干扰
//                    omcBillItemMapper.delete(billItemDto);
//                }
                for (OmcBillItem billItem : billItemList) {//填充账单ID及机构ID信息
                    billItem.setGroupId(groupId);
                    billItem.setBillId(billId);
                    billItem.setUpdateInfo(loginAuthDto);
                }
                omcBillItemService.batchSave(billItemList);
            }
            //插入套餐信息
            if (null != omcBillMeal.getSetMealId()) {
                omcBillMeal.setGroupId(groupId);
                omcBillMeal.setBillId(billId);
                omcBillMeal.setUpdateInfo(loginAuthDto);
//                if (omcBillMealMapper.selectCount(billMealDto) > 0) {//该账单已有的套餐信息记录删除,避免干扰
//                    omcBillMealMapper.delete(billMealDto);
//                }
                int ret = omcBillMealService.save(omcBillMeal);

                if (omcBillMeal.getBillSetMealItemList() != null && omcBillMeal.getBillSetMealItemList().size() > 0) {
                    List<OmcBillSetMealItem> itemList = omcBillMeal.getBillSetMealItemList();
                    for (OmcBillSetMealItem item : itemList) {
                        item.setGroupId(groupId);
                        item.setBillId(billId);
                        item.setUpdateInfo(loginAuthDto);
                    }
                    int retBatchInsert = omcBillSetMealItemService.batchSave(itemList);
                }
            }
            //插入入院账单费用统计
            billInHospitalFee.setGroupId(groupId);
            billInHospitalFee.setBillId(billId);
            billInHospitalFee.setUpdateInfo(loginAuthDto);
            omcBillInHospitalFeeMapper.insertSelective(billInHospitalFee);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 保存出院账单
     *
     * @param oldManBill         账单基础信息
     * @param billItemList       缴费项目信息
     * @param billBackItemList   退费项目信息
     * @param billOutHospitalFee 出院账单费用统计
     * @param loginAuthDto       登录人信息
     * @return
     */
    @Override
    public boolean saveOutHospitalBill(OmcOldManBill oldManBill, List<OmcBillItem> billItemList, List<OmcBillBackItem> billBackItemList, OmcBillOutHospitalFee billOutHospitalFee, LoginAuthDto loginAuthDto) {
        if (null == oldManBill) {
            return false;
        }
        if (null == billOutHospitalFee) {
            return false;
        }

        //查询老人名字
        Oldman oldman = new Oldman();
        oldman.setOldmanId(oldManBill.getOldManId().intValue());
        Oldman old = oldmanService.selectByOld(oldman);

        //查询床位和房间编号
        OldmanBedInfoVo oldmanBedInfoVo = bedService.selectByOid(oldManBill.getOldManId().intValue());
        String bedNo = String.valueOf(oldmanBedInfoVo.getBedNo());
        String roomNo = String.valueOf(oldmanBedInfoVo.getRoomNo());



        Long groupId = loginAuthDto.getGroupId();
        oldManBill.setBillNumber(DateUtil.getPayNumber(groupId));//账单号
        oldManBill.setBillType(2);//账单类型 1.入院账单 2.出院账单 3.调整账单 4.周期账单
        oldManBill.setUpdateInfo(loginAuthDto);
        oldManBill.setOldManName(old.getOldName());
        oldManBill.setBedNo(bedNo);
        oldManBill.setRoomNo(roomNo);
        int n = omcOldManBillMapper.insertSelective(oldManBill);//生成订单基础信息
        if (n > 0) {
            Long billId = oldManBill.getId();//账单ID
            //插入缴费项目信息
            if (null != billItemList && billItemList.size() > 0) {
                OmcBillItem billItemDto = new OmcBillItem();
                billItemDto.setGroupId(groupId);
                billItemDto.setBillId(billId);
                if (omcBillItemMapper.selectCount(billItemDto) > 0) {//该账单已有缴费项目记录删除,避免干扰
                    omcBillItemMapper.delete(billItemDto);
                }
                for (OmcBillItem billItem : billItemList) {//填充账单ID及机构ID信息
                    billItem.setGroupId(groupId);
                    billItem.setBillId(billId);
                    billItem.setUpdateInfo(loginAuthDto);
                    omcBillItemMapper.insertSelective(billItem);
                }
            }
            //插入退费项目信息
            if (null != billBackItemList && billBackItemList.size() > 0) {
                OmcBillBackItem billBackItemDto = new OmcBillBackItem();
                billBackItemDto.setGroupId(groupId);
                billBackItemDto.setBillId(billId);
                if (omcBillBackItemMapper.selectCount(billBackItemDto) > 0) {//该账单已有的退费项目信息记录删除,避免干扰
                    omcBillBackItemMapper.delete(billBackItemDto);
                }
                for (OmcBillBackItem billBackItem : billBackItemList) {//填充账单ID及机构ID信息
                    billBackItem.setGroupId(groupId);
                    billBackItem.setBillId(billId);
                    billBackItem.setUpdateInfo(loginAuthDto);
                    omcBillBackItemMapper.insertSelective(billBackItem);
                }
            }
            //插入入院账单费用统计
            billOutHospitalFee.setGroupId(groupId);
            billOutHospitalFee.setBillId(billId);
            billOutHospitalFee.setUpdateInfo(loginAuthDto);
            omcBillOutHospitalFeeMapper.insertSelective(billOutHospitalFee);
        } else {
            return false;
        }
        return true;
    }

    /**
     * 保存调整账单
     *
     * @param oldManBill    账单基础信息
     * @param billItemList  缴费项目
     * @param billAdjustFee 调整账单费用统计
     * @param loginAuthDto  登录人信息
     * @return
     */
    @Override
    public boolean saveAdjustBill(OmcOldManBill oldManBill, List<OmcBillItem> billItemList, OmcBillAdjustFee billAdjustFee, LoginAuthDto loginAuthDto) {
        if (null == oldManBill) {
            return false;
        }
        if (null == billAdjustFee) {
            return false;
        }
        Long groupId = loginAuthDto.getGroupId();
        oldManBill.setBillNumber(DateUtil.getPayNumber(groupId));//账单号
        oldManBill.setBillType(3);//账单类型 1.入院账单 2.出院账单 3.调整账单 4.周期账单
        oldManBill.setUpdateInfo(loginAuthDto);
        int n = omcOldManBillMapper.insertSelective(oldManBill);//生成订单基础信息
        if (n > 0) {
            Long billId = oldManBill.getId();//账单ID
            //插入缴费项目信息
            if (null != billItemList && billItemList.size() > 0) {
                OmcBillItem billItemDto = new OmcBillItem();
                billItemDto.setGroupId(groupId);
                billItemDto.setBillId(billId);
                if (omcBillItemMapper.selectCount(billItemDto) > 0) {//该账单已有缴费项目记录删除,避免干扰
                    omcBillItemMapper.delete(billItemDto);
                }
                for (OmcBillItem billItem : billItemList) {//填充账单ID及机构ID信息
                    billItem.setGroupId(groupId);
                    billItem.setBillId(billId);
                    billItem.setUpdateInfo(loginAuthDto);
                    omcBillItemMapper.insertSelective(billItem);
                }
            }
            //插入调整账单费用统计
            billAdjustFee.setGroupId(groupId);
            billAdjustFee.setBillId(billId);
            billAdjustFee.setUpdateInfo(loginAuthDto);
            omcBillAdjustFeeMapper.insertSelective(billAdjustFee);
        } else {
            return false;
        }
        return true;
    }

    /**
     * 保存周期账单
     *
     * @param oldManBill    账单基础信息
     * @param billItemList  缴费项目
     * @param billPeriodFee 周期账单费用统计
     * @param loginAuthDto  登录人信息
     * @return
     */
    @Override
    public Long savePeriodBill(OmcOldManBill oldManBill, List<OmcBillItem> billItemList, OmcBillPeriodFee billPeriodFee, LoginAuthDto loginAuthDto) {
        Long billId = 0L;
        if (null == oldManBill) {
            return billId;
        }
        if (null == billPeriodFee) {
            return billId;
        }

        Oldman oldman = new Oldman();
        oldman.setOldmanId(oldManBill.getOldManId().intValue());
        Oldman old = oldmanService.selectByOld(oldman);

        OldmanBedInfoVo oldmanBedInfoVo = bedService.selectByOid(oldManBill.getOldManId().intValue());
        String bedNo = String.valueOf(oldmanBedInfoVo.getBedNo());
        String roomNo = String.valueOf(oldmanBedInfoVo.getRoomNo());


        Long groupId = loginAuthDto.getGroupId();
        oldManBill.setBillNumber(DateUtil.getPayNumber(groupId));//账单号
        oldManBill.setBillType(4);//账单类型 1.入院账单 2.出院账单 3.调整账单 4.周期账单
        oldManBill.setUpdateInfo(loginAuthDto);
        oldManBill.setOldManName(old.getOldName());
        oldManBill.setBedNo(bedNo);
        oldManBill.setRoomNo(roomNo);


        int n = omcOldManBillMapper.insertSelective(oldManBill);//生成订单基础信息
        if (n > 0) {
            billId = oldManBill.getId();//账单ID
            //插入缴费项目信息
            if (null != billItemList && billItemList.size() > 0) {
                OmcBillItem billItemDto = new OmcBillItem();
                billItemDto.setGroupId(groupId);
                billItemDto.setBillId(billId);
                if (omcBillItemMapper.selectCount(billItemDto) > 0) {//该账单已有缴费项目记录删除,避免干扰
                    omcBillItemMapper.delete(billItemDto);
                }
                for (OmcBillItem billItem : billItemList) {//填充账单ID及机构ID信息
                    billItem.setGroupId(groupId);
                    billItem.setBillId(billId);
                    billItem.setUpdateInfo(loginAuthDto);
                    omcBillItemMapper.insertSelective(billItem);
                }
            }
            //插入周期账单费用统计
            billPeriodFee.setGroupId(groupId);
            billPeriodFee.setBillId(billId);
            billPeriodFee.setUpdateInfo(loginAuthDto);
            omcBillPeriodFeeMapper.insertSelective(billPeriodFee);
        } else {
            return billId;
        }
        return billId;
    }


    /**
     * 计算周期费用,并添加周期账单
     * <p>
     * 备注:生成周期账单的前提条件:1.机构有配置周期账单生成时间  2.机构有配置退费方案 3.老人已入院并且有入院信息 4.老人账户资金有信息
     *
     * @param groupId
     * @return
     */
    @Override
    public void addPeriodBill(Long groupId) {
        //查询上次执行定时任务的时间,用于查询本周期内的老人请假情况
        //查询周期设置
        OmcPaymentCycle paymentCycleDto = new OmcPaymentCycle();
        paymentCycleDto.setGroupId(groupId);
        OmcPaymentCycle paymentCycle = paymentCycleService.selectOne(paymentCycleDto);
        if (null == paymentCycle) {//如果没有缴费单生成周期配置,不进行周期账单生成
            return;
        }
        //上次定时任务执行时间
        Date lastDate = CronUtil.getLastTriggerTime(paymentCycle.getPaymentRecordGenerateConfig());
        if (null == lastDate) {//如果上次定时任务执行时间为空,则表示配置的cron表达式错误
            return;
        }
        //查询是否有退费方案,没有退费方案不予生成周期账单,一个机构只有一个退费方案配置
        OmcReturnFeeConfig dto = new OmcReturnFeeConfig();
        dto.setGroupId(groupId);
        OmcReturnFeeConfig returnFeeConfig = returnFeeConfigService.selectOne(dto);
        if (null != returnFeeConfig) {//配置了退费方案才进行周期账单生成
            //查询需要生成周期账单的老人,已入院状态的老人
            Oldman oldman = new Oldman();
            oldman.setHomeId(groupId.intValue());
            oldman.setStatus(3);//已入院状态
            List<OldManSupVo> oldManList = oldmanMapper.selectOldManSup(oldman);
            if (null != oldManList && oldManList.size() > 0) {
                for (OldManSupVo oldManSupVo : oldManList) {
                    Long oldManId = oldManSupVo.getOldmanId();
                    //查询老人账户资金信息,入院老人都有账户资金信息
                    OmcOldManAccountFunds accountFundsDto = new OmcOldManAccountFunds();
                    accountFundsDto.setOldManId(oldManId);
                    accountFundsDto.setGroupId(groupId);
                    OmcOldManAccountFunds accountFunds = accountFundsService.selectOne(accountFundsDto);
                    if (null == accountFunds) {
                        continue;
                    }
                    if (null != oldManSupVo.getInDate() && !"".equals(oldManSupVo.getInDate())) {
                        //入院时间不为空,才能生成周期账单
                        Date inDate = null;
                        try {
                            inDate = DateUtil.getDate(oldManSupVo.getInDate());
                        } catch (ParseException e) {
                            continue;
                        }
                        if (null != inDate) {
                            //准备入参参数
                            BigDecimal unpayCycle = new BigDecimal(0);//欠缴周期数
                            BigDecimal beforeProduceBalance = accountFunds.getRemainder();//账单生成前余额
                            BigDecimal afterProduceBalance = new BigDecimal(0);//账单生成后余额
                            BigDecimal theWeekPayFee = new BigDecimal(0);//本周缴费金额
                            BigDecimal lastWeekBackFee = new BigDecimal(0);//上周退费金额
                            BigDecimal lastWeekOweFee = new BigDecimal(0);//上周欠缴费用
                            BigDecimal totalFee = new BigDecimal(0);//应交合计
                            BigDecimal leaveDegree = new BigDecimal(0);//已请假退费的周期数
                            OmcOldManBill oldManBill = new OmcOldManBill();//周期缴费单
                            oldManBill.setOldManId(oldManId);
                            List<OmcBillItem> billItemList = new ArrayList<>();//周期缴费项目
                            OmcBillPeriodFee billPeriodFee = new OmcBillPeriodFee();//周期账单费用统计
                            //开始计算周期费用
                            //计算欠缴周期数
                            int days = DateUtil.differentDays(new Date(), inDate);//实际入院天数
                            if (returnFeeConfig.getCycleMaxDays() > days) {
                                //当周期最大天数大于实际入院天数时,欠缴周期数才不会为0  欠缴周期数 = (周期最大天数 - 实际入院天数)/周期总天数
                                unpayCycle = new BigDecimal(returnFeeConfig.getCycleMaxDays() - days).divide(new BigDecimal(returnFeeConfig.getCycleTotalDays()), 2, BigDecimal.ROUND_HALF_UP);
                            }
                            //计算请假周期数
                            //查询老人请假信息
                            Map<String, Object> paramMap = new HashMap<>();
                            paramMap.put("groupId", groupId);
                            paramMap.put("lastDate",DateUtil.dateToString(lastDate) );
                            paramMap.put("oldManId", oldManId);
                            List<OmcOldLeave> oldLeavelist = oldLeaveService.selectOldLeaveList(paramMap);
                            //统计老人周期请假需退费的天数,配置的请假退费天数（大于等于该天数才进行退费,配置的扣除请假天数（当满足退费天数时，要扣除该天数的金额）
                            //计算请假退费
                            if (null != oldLeavelist && oldLeavelist.size() > 0) {
                                for (OmcOldLeave oldLeave : oldLeavelist) {
                                    lastWeekBackFee.add(oldLeave.getRefundFee());
                                    if(null != oldLeave.getReturnDegree()){
                                        leaveDegree = leaveDegree.add(oldLeave.getReturnDegree());
                                    }
                                    //可计算的退费天数置空
                                    oldLeave.setRealRefundDays(0);
                                }
                            }
                            //查询老人的周期项目
                            OmcCycleExpenseItem cycleExpenseItemDto = new OmcCycleExpenseItem();
                            cycleExpenseItemDto.setGroupId(groupId);
                            cycleExpenseItemDto.setOldmanId(oldManId);
                            List<OmcCycleExpenseItem> cycleExpenseItemList = cycleExpenseItemService.select(cycleExpenseItemDto);
                            //开始计算周期费用
                            if (null != cycleExpenseItemList && cycleExpenseItemList.size() > 0) {
                                for (OmcCycleExpenseItem item : cycleExpenseItemList) {
                                    OmcBillItem billItem = new OmcBillItem();//收集周期项目数据,用于入库展示
                                    BigDecimal residueDegree = item.getResidueDegree();//项目剩余周期数
                                    //实际剩余周期数 = 项目剩余周期数减去请假退费周期数
                                    residueDegree = residueDegree.subtract(leaveDegree).compareTo(BigDecimal.ZERO) == -1 ? BigDecimal.ZERO : residueDegree.subtract(leaveDegree);
                                    if (residueDegree.compareTo(BigDecimal.ZERO) == 1) {//项目剩余周期数大于O
                                        if (residueDegree.compareTo(BigDecimal.ONE) == -1) {//剩余周期数小于1
                                            //计算本周期费用
                                            theWeekPayFee = theWeekPayFee.add(item.getActualFee().multiply(BigDecimal.ONE.subtract(residueDegree)));//本周周期缴费 = 项目实际费用*(1-剩余周期数)
                                            residueDegree = new BigDecimal(0);//剩余周期数归零
                                        } else {//剩余周期数大于等于1
                                            residueDegree = residueDegree.subtract(BigDecimal.ONE);//剩余周期数减去1,本周周期项目缴费为0
                                        }
                                        if (residueDegree.compareTo(unpayCycle) == -1) {//剩余周期数小于欠缴周期数
                                            lastWeekOweFee = lastWeekOweFee.add(item.getActualFee().multiply(unpayCycle.subtract(residueDegree)));//上周欠缴费用 = 项目实际费用*(欠缴周期数 - 剩余周期数)
                                            residueDegree = new BigDecimal(0);//剩余周期数归零
                                        } else {//剩余周期数大于等于欠缴周期数
                                            residueDegree = residueDegree.subtract(unpayCycle);//剩余周期数要去掉欠缴周期数
                                        }
                                    } else {//项目剩余周期数小于等于0
                                        theWeekPayFee = theWeekPayFee.add(item.getActualFee());//本周周期缴费
                                        lastWeekOweFee = lastWeekOweFee.add(item.getActualFee().multiply(unpayCycle));//上周欠缴费用 = 项目实际费用*欠缴周期数
                                    }
                                    //开始填充周期项目数据
                                    billItem.setGroupId(groupId);//机构ID
                                    billItem.setItemFee(item.getItemFee());//项目费用
                                    billItem.setItemType(item.getItemType());//缴费类型名
                                    billItem.setItemName(item.getItemName());//缴费项目名
                                    billItem.setUserTypeRateRefief(item.getUserTypeRateRefief());//人员类别减免费用
                                    billItem.setUserRateRefief(item.getUserRateRefief());//人工减免费用
                                    billItem.setActualFee(item.getActualFee());//项目实际费用
                                    billItemList.add(billItem);
                                    //跟新周期项目信息,主要是改变周期剩余数
                                    item.setResidueDegree(residueDegree);
                                    item.setUpdateInfo(getLoginAuthDto());
                                    cycleExpenseItemService.update(item);
                                }
                            }
                            //形成参数,保存周期账单
                            //周期应交合计  周期应交 = 本周期缴费金额 - 缴费单生成前余额-上周期退费金额 + 上周期欠缴金额
                            totalFee = totalFee.add(theWeekPayFee.subtract(beforeProduceBalance).subtract(lastWeekBackFee).add(lastWeekOweFee));
                            totalFee = totalFee.compareTo(BigDecimal.ZERO) == -1 ? BigDecimal.ZERO : totalFee;//应交合计<0时,应交合计为零
                            //账单生成后余额 账单生成后余额 = 账单生成前余额 - 周期应交合计
                            afterProduceBalance = afterProduceBalance.add(beforeProduceBalance.subtract(totalFee));
                            billPeriodFee.setBeforeProduceBalance(beforeProduceBalance.setScale(2));
                            billPeriodFee.setAfterProduceBalance(afterProduceBalance.setScale(2));
                            billPeriodFee.setLastWeekBackFee(lastWeekBackFee.setScale(2));
                            billPeriodFee.setTheWeekPayFee(theWeekPayFee.setScale(2));
                            billPeriodFee.setLastWeekOweFee(lastWeekOweFee.setScale(2));
                            billPeriodFee.setTotalFee(totalFee.setScale(2));
                            //账单基础
                            oldManBill.setTotalPay(totalFee.setScale(2));
                            Long billId = savePeriodBill(oldManBill, billItemList, billPeriodFee, getLoginAuthDto());
                            //修改老人账单资金信息
                            if (billId > 0) {//周期账单生成成功
                                accountFunds.setMonetary(accountFunds.getMonetary().add(beforeProduceBalance.subtract(afterProduceBalance)));//总消费额
                                accountFunds.setRemainder(afterProduceBalance);//余额
                                accountFunds.setUpdateInfo(getLoginAuthDto());
                                accountFundsService.update(accountFunds);
                                //修改请假的退费天数
                                oldLeaveService.batchUpdate(oldLeavelist);
                            }
                        }
                    }
                }
            }

        }
    }


    public void createCycleBill(CycleBillDto cycleBillDto, LoginAuthDto loginAuthDto) {

        try {

            String cycleDate = cycleBillDto.getCycleDate();
            Integer oldmanId = cycleBillDto.getOldmanId();
            Long groupId = loginAuthDto.getGroupId();
//        String inDate = cycleBillDto.getInDate();

            // 周期消费金额 = 本周期预缴金额 - 上周期退费金额

            // 上周期退费金额 = 上周期的请假记录的请假退费金额之和 （多次请假退费存在问题）

            // 本周期预缴金额

            /**
             * 本周期预缴优先扣除套餐剩余次数，然后在扣除账户余额
             *
             * 周期缴费前余额 = 上次缴费单生成后的余额
             * 当前套餐剩余周期数 = 上次缴费单生成后的周期数
             */

            // 根据日期查询上一个预缴周期数 （usedPercent）
//        CheckInDaysDto checkInDaysDto = new CheckInDaysDto();
//        checkInDaysDto.setGroupId(groupId);
//        checkInDaysDto.setCheckInDate(com.csun.cmny.util.DateUtil.stringToDate(inDate));
//        CheckInDaysVo checkInDaysVo = returnFeeConfigService.queryCheckInDaysVo(checkInDaysDto);
//        String next_date = com.csun.cmny.util.DateUtil.getDateStr(checkInDaysVo.getNextDate());
//        BigDecimal usedPercent = BigDecimal.ZERO;
//        if (next_date.compareTo(cycleDate) == 0) {
//            usedPercent = checkInDaysVo.getPayPercent();
//        }

//        log.info("上一个预缴周期数 usedPercent = {}", usedPercent);
            /**
             * 本周期预缴一个周期数；
             *
             * 对比套餐剩余周期数：
             *
             * 套餐剩余周期数 TS = 已使用 + 待使用 - 上一预缴周期数（入院当月剩余，周期为1）
             *
             * 如果剩余周期数 < 0, 说明无周期可以使用，如果 > 0，则按照下述描述进行消耗
             *
             * 如果 TS >= 1 (套餐可以满足周期消耗)
             *
             * 本周预缴金额 = 非套餐周期收费项 * 收费项原价 * 1 + ...
             *
             * 套餐使用数 = 1，剩余周期数 = TS - 1
             *
             * 如果 TS < 1 (套餐不够周期消耗)
             *
             * 本周期预缴金额 = 非套餐周期收费项 * 收费项原价 * 1 + ... + 套餐收费项 * 收费项原价 * (1 - TS)
             *
             * 套餐使用数 = TS， 剩余周期数为 0
             */

            /**
             * 总结
             *
             * 本周期预缴套餐数 = (TS >= 1) ? 1 : TS
             *
             * 本周期预缴金额 =
             * (TS >= 1) ? (套餐外项目金额 * 1 周期) : ((套餐内项目原价) * (1 - Ts) + (套餐外项目金额)*1)
             *
             * 周期缴费单生成后套餐剩余周期数 =  Ts - 本周期预缴套餐数;
             */

            // 根据老人Id查询周期缴费信息
            GroupPaymentFeeQueryDto groupPaymentFeeQueryDto = new GroupPaymentFeeQueryDto();
            groupPaymentFeeQueryDto.setOldmanId(oldmanId);
            List<OldmanPaymentFeeVo> oldmanPaymentFeeVoList = omcCycleExpenseItemMapper
                    .queryOldmanPaymentFeeByOldmanId(groupPaymentFeeQueryDto);
            Map<Long, OmcBillItem> omcBillItemMap = Maps.newHashMap();
            if (PublicUtil.isEmpty(oldmanPaymentFeeVoList)) {
                log.warn("老人无缴费信息");
            } else {
                for (OldmanPaymentFeeVo opfv : oldmanPaymentFeeVoList) {
                    OmcBillItem omcBillItem = getOmcBillItem(opfv, loginAuthDto, BigDecimal.ONE);
                    omcBillItem.setGroupId(groupId);
                    omcBillItemMap.put(opfv.getExpenseItemId(), omcBillItem);
                }
            }

            Long billId = omcOldManBillService.queryOldmanCheckInBillId(oldmanId);
            if (billId == null) {
                throw new OmcBizException(ErrorCodeEnum.OMC10038042);
            }
            // 根据老人Id查询套餐缴费信息

            // 用于标记是否调整前的收费项进行差额计算
            List<OldmanSetMealVo> oldmanSetMealVoList = omcBillMealService.queryOldmanSetMealByBillId(billId);

            //查询老人名字
            Oldman oldman = new Oldman();
            oldman.setOldmanId(oldmanId);
            Oldman old = oldmanService.selectByOld(oldman);

            //查询床位信息
            OldmanBedInfoVo oldmanBedInfoVo = bedService.selectByOid(oldmanId);

            OmcOldManBill omcOldManBill = new OmcOldManBill();
            omcOldManBill.setUpdateInfo(loginAuthDto);
            omcOldManBill.setOldManId((long) oldmanId);
            String billNumber = DateUtil.getPayNumber(groupId); // 缴费单号
            omcOldManBill.setBillNumber(billNumber);
            omcOldManBill.setBillType(4); // 周期账单
            omcOldManBill.setAdvanceCycle(1l);
            omcOldManBill.setGroupId(groupId);
            omcOldManBill.setOldManName(old.getOldName());
            omcOldManBill.setInDate(cycleBillDto.getInDate());
            String bedNo = String.valueOf(oldmanBedInfoVo.getBedNo());
            String roomNo = String.valueOf(oldmanBedInfoVo.getRoomNo());
            omcOldManBill.setBedNo(bedNo);
            omcOldManBill.setRoomNo(roomNo);
            if (PublicUtil.isNotEmpty(cycleBillDto.getCreateTime())) {
                omcOldManBill.setCreatedTime(cycleBillDto.getCreateTime());
                omcOldManBill.setUpdateTime(cycleBillDto.getCreateTime());
            }
            // omcOldManBill.setIsPassed(0);   // 待确认
            omcOldManBill.setIsConfirm(0);


            omcOldManBillService.save(omcOldManBill);

            billId = omcOldManBill.getId();
            List<OmcBillMeal> omcBillMealList = Lists.newArrayList();
            List<OmcBillSetMealItem> omcBillSetMealItemList = Lists.newArrayList();
            for (OldmanSetMealVo osmv : oldmanSetMealVoList) {
                OmcBillMeal omcBillMeal = getOmcBillMeal(osmv, loginAuthDto);
                omcBillMeal.setGroupId(groupId);
                omcBillMeal.setBillId(billId);
                omcBillMealList.add(omcBillMeal);
                for (OldmanSetMealItemVo osmiv : osmv.getOldmanSetMealItemVoList()) {
                    OmcBillSetMealItem omcBillSetMealItem = getOmcBillSetMealItem(osmiv, loginAuthDto);
                    omcBillSetMealItem.setGroupId(groupId);
                    omcBillSetMealItem.setBillId(billId);
                    omcBillSetMealItem.setSetmealId(osmv.getSetMealId());
                    // BigDecimal TS = osmiv.getUsedDegree().add(osmiv.getResidueDegree()).subtract(usedPercent);
                    BigDecimal TS = osmiv.getResidueDegree();
                    OmcBillItem omcBillItem = omcBillItemMap.get(osmiv.getExpenseItemId());
                    if (PublicUtil.isEmpty(omcBillItem)) {
                        log.warn("套餐不进行周期费用计算...");
                    } else {
                        // 套餐剩余数
                        if (TS.compareTo(BigDecimal.ZERO) <= 0) {
                            // 套餐在上一个周期使用完了
                        } else {
                            //
                            if (TS.compareTo(BigDecimal.ONE) >= 0) {
                                // 使用套餐
                                omcBillSetMealItem.setUsedDegree(BigDecimal.ONE);
                                omcBillSetMealItem.setResidueDegree(TS.subtract(BigDecimal.ONE));
                                omcBillItemMap.remove(osmiv.getExpenseItemId());
                            } else {
                                // 部分使用原价
                                omcBillSetMealItem.setUsedDegree(TS);
                                omcBillSetMealItem.setResidueDegree(BigDecimal.ZERO);

                                // 部分使用套餐
                                omcBillItem.setUsedDegree(BigDecimal.ONE.subtract(TS));
                                omcBillItem.setResidueDegree(BigDecimal.ZERO);
                            }
                        }
                    }
                    omcBillSetMealItemList.add(omcBillSetMealItem);
                }
            }
            omcBillMealService.batchSave(omcBillMealList);
            omcBillSetMealItemService.batchSave(omcBillSetMealItemList);

            // 本周期预缴金额 payTotal
            BigDecimal advancePayFee = BigDecimal.ZERO;
            List<OmcBillItem> omcBillItemList = Lists.newArrayList();
            for (OmcBillItem value : omcBillItemMap.values()) {
                log.info("id = {}, name = {}, fee = {}, percend = {}",
                        value.getExpenseItemId(), value.getItemName(), value.getItemFee(), value.getUsedDegree());
                BigDecimal total = value.getUsedDegree().multiply(value.getActualFee()).setScale(2, BigDecimal.ROUND_HALF_UP);
                advancePayFee = advancePayFee.add(total);
                value.setBillId(billId);
                omcBillItemList.add(value);
            }
            log.info("advancePayFee = {}", advancePayFee);
            omcBillItemService.batchSave(omcBillItemList);

            // TODO 计算请假退费
            OmcOldLeaveQueryDto omcOldLeaveQueryDto = new OmcOldLeaveQueryDto();
            omcOldLeaveQueryDto.setOldManId(oldmanId.longValue());
            omcOldLeaveQueryDto.setAdjustDate(cycleDate);
            omcOldLeaveQueryDto.setGroupId(groupId);
            OmcAdjustRefundData omcAdjustRefundData = oldLeaveService.showLeaveRefundFee(omcOldLeaveQueryDto);

            if (omcAdjustRefundData == null) {
                omcAdjustRefundData = new OmcAdjustRefundData();
            }
            // 周期消费金额 =  本周期预缴金额 - 上周期退费金额
            BigDecimal cycleUsedFee = advancePayFee.subtract(omcAdjustRefundData.getRefundFee());

            // 老人资金账户
            OmcOldManAccountFunds omcOldManAccountFunds = accountFundsService
                    .queryByOldmanId(oldmanId);
            if (PublicUtil.isEmpty(omcOldManAccountFunds)) {
                throw new OmcBizException(ErrorCodeEnum.OMC10038030);
            }

            // 预缴费用
            omcOldManBill.setAdvancePayFee(advancePayFee);

            BigDecimal before = omcOldManAccountFunds.getRemainder();
            BigDecimal after = before.subtract(cycleUsedFee);

            // 应交合计 = (周期消费金额 - 账户余额) > 0 ? (周期消费金额 - 账户余额) : 0
            BigDecimal totalPay = cycleUsedFee.subtract(before);
            if (totalPay.compareTo(BigDecimal.ZERO) < 0) {
                totalPay = BigDecimal.ZERO;
            }
            omcOldManBill.setTotalPay(totalPay);
            omcOldManBillService.update(omcOldManBill);

            // 周期账单费用统计表
            OmcBillPeriodFee omcBillPeriodFee = new OmcBillPeriodFee();
            omcBillPeriodFee.setGroupId(groupId);
            omcBillPeriodFee.setBillId(billId);
            omcBillPeriodFee.setAfterProduceBalance(after);  // 账单后的余额
            omcBillPeriodFee.setBeforeProduceBalance(before); // 账单前的余额
            omcBillPeriodFee.setTheWeekPayFee(advancePayFee);        // 本周缴费金额
            omcBillPeriodFee.setLastWeekBackFee(omcAdjustRefundData.getRefundFee());      // 上周期退费金额
            if (before.compareTo(BigDecimal.ZERO) < 0) {
                omcBillPeriodFee.setLastWeekOweFee(before);       // 上周欠缴金额
            } else {
                omcBillPeriodFee.setLastWeekOweFee(BigDecimal.ZERO);       // 上周欠缴金额
            }

            omcBillPeriodFee.setTotalFee(totalPay);             // 实际合计费用
            omcBillPeriodFeeMapper.insertSelective(omcBillPeriodFee);

            omcOldManAccountFunds.setRemainder(after);
            omcOldManAccountFunds.setMonetary(omcOldManAccountFunds.getMonetary().add(cycleUsedFee));
            omcOldManAccountFunds.setActPaidFee(omcOldManAccountFunds.getActPaidFee().add(totalPay));
            omcOldManAccountFunds.setUpdateInfo(loginAuthDto);

            // 老人请假退费结算
            oldLeaveService.closeReturnFeeByDate(oldmanId, cycleDate);

            accountFundsService.update(omcOldManAccountFunds);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private OmcBillSetMealItem getOmcBillSetMealItem(OldmanSetMealItemVo osmiv, LoginAuthDto loginAuthDto) {

        OmcBillSetMealItem omcBillSetMealItem = new OmcBillSetMealItem();

        BeanUtils.copyProperties(osmiv, omcBillSetMealItem);
        omcBillSetMealItem.setUpdateInfo(loginAuthDto);

        return omcBillSetMealItem;
    }

    private OmcBillMeal getOmcBillMeal(OldmanSetMealVo osmv, LoginAuthDto loginAuthDto) {

        OmcBillMeal omcBillMeal = new OmcBillMeal();

        BeanUtils.copyProperties(osmv, omcBillMeal);
        omcBillMeal.setUpdateInfo(loginAuthDto);
        omcBillMeal.setMealName(osmv.getSetMealName());
        omcBillMeal.setOriginFee(osmv.getOriginalPrice());
        omcBillMeal.setRateRefief(osmv.getSubPrice());
        omcBillMeal.setActualFee(osmv.getActualPrice());

        return omcBillMeal;
    }

    private OmcBillItem getOmcBillItem(OldmanPaymentFeeVo opfv, LoginAuthDto loginAuthDto, BigDecimal cycleNumber) {

        OmcBillItem omcBillItem = new OmcBillItem();

        BeanUtils.copyProperties(opfv, omcBillItem);
        omcBillItem.setUpdateInfo(loginAuthDto);
        omcBillItem.setUsedDegree(cycleNumber);
        omcBillItem.setResidueDegree(BigDecimal.ZERO);

        return  omcBillItem;
    }

    /**
     * 账单缴费
     *
     * @param omcOldManBillDto
     * @param loginAuthDto
     * @return
     */
    @Override
    public boolean payFee(OmcOldManBillDto omcOldManBillDto, LoginAuthDto loginAuthDto) {
        //根据账单ID查询账单详情
        OmcOldManBillDto dto = new OmcOldManBillDto();
        dto.setBillId(omcOldManBillDto.getBillId());
        OmcOldManBillDetailVo oldManBillDetailVo = queryBillDetail(dto);
        if (PublicUtil.isEmpty(oldManBillDetailVo)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10037028);
        }
        //查询老人账户资金信息,入院老人都有账户资金信息
        OmcOldManAccountFunds accountFundsDto = new OmcOldManAccountFunds();
        accountFundsDto.setOldManId(oldManBillDetailVo.getOldManId());
        accountFundsDto.setGroupId(omcOldManBillDto.getGroupId());
        OmcOldManAccountFunds accountFunds = accountFundsService.selectOne(accountFundsDto);
        if (PublicUtil.isEmpty(accountFunds)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10037030);
        }
        if (oldManBillDetailVo.getIsPay() == 1) {
            throw new OmcBizException(ErrorCodeEnum.OMC10037031);
        }
        //缴费单
        OmcOldManBill omcOldManBill = new OmcOldManBill();
        omcOldManBill.setId(oldManBillDetailVo.getId());
        omcOldManBill.setGroupId(omcOldManBillDto.getGroupId());
        omcOldManBill.setPayTime(new Date());
        omcOldManBill.setIsPay(1);
        //账单类型 1.入院账单 2.出院账单 3.调整账单 4.周期账单
        if (oldManBillDetailVo.getBillType() == 1) {//入院账单

            //校验入院项目是否与缴费单一致
            OmcOldmanExpenseItem query = new OmcOldmanExpenseItem();
            query.setOldmanId(oldManBillDetailVo.getOldManId());
            List<OmcOldmanExpenseItem> itemList = omcOldmanExpenseItemService.select(query);
            if(itemList.size() < 1){
                throw new OmcBizException(ErrorCodeEnum.OMC10037035);
            }else{
                if(!itemList.get(0).getStatus().equals(1)){
                    throw new OmcBizException(ErrorCodeEnum.OMC10037036);
                }
            }

            //查询老人缴费单信息
            OmcOldManBill oldManBill = omcOldManBillService.selectByKey(omcOldManBillDto.getBillId());
            OmcOldManSupplement osQuery = new OmcOldManSupplement();
            osQuery.setOldManId(oldManBill.getOldManId());
            osQuery = omcOldManSupplementService.selectOne(osQuery);

            //校验缴费单审批是否通过
            if (!oldManBill.getIsPassed().equals(1)) {
                throw new OmcBizException(ErrorCodeEnum.OMC10037043);
            }

            //更改老人状态为试入住
            Oldman oldman = new Oldman();
            oldman.setOldmanId(oldManBill.getOldManId().intValue());
            oldman = oldmanService.selectByOld(oldman);
            oldman.setStatus(5);
            oldmanService.updateByOldId(oldman);

            Bed bedQuery = new Bed();
            bedQuery.setOldmanId(oldManBill.getOldManId().intValue());
            bedQuery = bedService.selectByBed(bedQuery);
            bedQuery.setStatus(5);
            bedService.updateById(bedQuery);

            //设置老人支付状态为已经支付
            osQuery.setIsPayed(1);

            //判别选择项目中是否有押金
            OmcBillItem billItemQuery = new OmcBillItem();
            billItemQuery.setBillId(oldManBillDetailVo.getId());
            List<OmcBillItem> billItemList = omcBillItemService.select(billItemQuery);
            int flag = 0;
            for(OmcBillItem item : billItemList){
                //如果包含押金 将flag置1
                if(item.getCode().equals(3)){
                    flag = 1;
                }
            }

            if(flag == 1){
                if (PublicUtil.isEmpty(omcOldManBillDto.getCashPledgeNum())) {
                    throw new OmcBizException(ErrorCodeEnum.OMC10037029);
                }
                //校验押金编号唯一
                OmcOldManSupplement checkCashPledgeNum = new OmcOldManSupplement();
                checkCashPledgeNum.setInEpositNo(omcOldManBillDto.getCashPledgeNum());
                checkCashPledgeNum.setGroupId(loginAuthDto.getGroupId());
                int checkRet = omcOldManSupplementService.selectCount(checkCashPledgeNum);
                if(checkRet > 0){
                    throw new OmcBizException(ErrorCodeEnum.OMC10037053);
                }

                //将押金编号同步到老人额外信息表
                omcOldManBill.setCashPledgeNum(omcOldManBillDto.getCashPledgeNum());
                osQuery.setInEpositNo(omcOldManBillDto.getCashPledgeNum());
            }
            int retUpdateOldman = omcOldManSupplementService.update(osQuery);

            //缴费
            omcOldManBill.setUpdateInfo(loginAuthDto);
            int n = omcOldManBillMapper.updateByPrimaryKeySelective(omcOldManBill);
            if (n > 0) {
                //修改账户资金信息
//                accountFunds.setRemainder(accountFunds.getRemainder().add(oldManBillDetailVo.getAdvancePayFee()));//余额
//                accountFunds.setUpdateInfo(loginAuthDto);
//                accountFundsService.update(accountFunds);
                //修改老人入院状态及支付状态
//                Oldman oldman = new Oldman();
//                oldman.setOldmanId(oldManBillDetailVo.getOldManId().intValue());
//                oldman.setStatus(3);//入院状态
//                oldmanMapper.updateByPrimaryKeySelective(oldman);
                //修改支付状态
//                OmcOldManSupplement oldManSupplement = new OmcOldManSupplement();
//                oldManSupplement.setOldManId(oldManBillDetailVo.getOldManId());
//                oldManSupplement.setIsPayed(1);
//                oldManSupplementMapper.confirmPay(oldManSupplement);
                return true;
            }

        } else if (oldManBillDetailVo.getBillType() == 2) {//出院账单
            //缴费
            omcOldManBill.setUpdateInfo(loginAuthDto);
            int n = omcOldManBillMapper.updateByPrimaryKeySelective(omcOldManBill);
            if (n > 0) {
                //修改账户资金信息
                accountFunds.setRemainder(accountFunds.getRemainder().add(oldManBillDetailVo.getBillPeriodFee().getTotalFee()));//余额
                accountFunds.setUpdateInfo(loginAuthDto);
                accountFundsService.update(accountFunds);
                return true;
            }
        } else if (oldManBillDetailVo.getBillType() == 3) {//调整账单
            //缴费
            omcOldManBill.setUpdateInfo(loginAuthDto);
            int n = omcOldManBillMapper.updateByPrimaryKeySelective(omcOldManBill);
            if (n > 0) {
                //修改账户资金信息
                accountFunds.setRemainder(accountFunds.getRemainder().add(oldManBillDetailVo.getBillPeriodFee().getTotalFee()));//余额
                accountFunds.setUpdateInfo(loginAuthDto);
                accountFundsService.update(accountFunds);
                return true;
            }
        } else if (oldManBillDetailVo.getBillType() == 4) {//周期账单
            //缴费
            omcOldManBill.setUpdateInfo(loginAuthDto);
            int n = omcOldManBillMapper.updateByPrimaryKeySelective(omcOldManBill);
            if (n > 0) {
                //修改账户资金信息
                accountFunds.setRemainder(accountFunds.getRemainder().add(oldManBillDetailVo.getBillPeriodFee().getTotalFee()));//余额
                accountFunds.setUpdateInfo(loginAuthDto);
                accountFundsService.update(accountFunds);
                return true;
            }
        }
        return false;
    }

    /**
     * query oldman check in bill id
     *
     * @param oldmanId the oldman id
     * @return the oldman check in bill id the last time
     */
    @Override
    public Long queryOldmanCheckInBillId(Integer oldmanId) {

        return omcOldManBillMapper.queryOldmanCheckInBillId(oldmanId);
    }

    /**
     * 根据Id查询账单详情
     *
     * @param id 账单Id
     * @return 账单详情
     */
    @Override
    public Object queryBillById(Long id) {

        Map<String, Object> map = Maps.newHashMap();

        // 获取账单类型
        OmcOldManBill omcOldManBill = omcOldManBillMapper.selectByPrimaryKey(id);
        if (omcOldManBill == null) {
            log.warn("账单不存在");
            return null;
        }
        map.put("omcOldManBill", omcOldManBill);

        OmcOldManBillDto omcOldManBillDto = new OmcOldManBillDto();
        omcOldManBillDto.setBillId(id);

        OmcOldManBillDetailVo omcOldManBillDetailVo = new OmcOldManBillDetailVo();

        switch (omcOldManBill.getBillType()) {
            case Constant.BILL_TYPE_CHECK_IN :  // 入院账单详情
                omcOldManBillDetailVo = queryBillDetail(omcOldManBillDto);   // 使用之前的接口
                map.put("omcOldManBillDetailVo", omcOldManBillDetailVo);
                break;
            case Constant.BILL_TYPE_CHECK_OUT :  // 出院账单详情
                // 根据账单Id查询老人出院详情
                OldOutVo oldOutVo = omcOldOutService.queryByBillId(id);
                map.put("oldOutVo", oldOutVo);
                map.put("billNumber", omcOldManBill.getBillNumber());
                break;
            case Constant.BILL_TYPE_REVISE :  // 调整账单详情
                ReviseVo reviseVo = omcReviseService.queryByBillId(id);
                map.put("reviseVo", reviseVo);
                map.put("billNumber", omcOldManBill.getBillNumber());
                /**
                 * 查询调整前后的余额
                 */
                OmcBillAdjustFee omcBillAdjustFee = new OmcBillAdjustFee();
                omcBillAdjustFee.setBillId(id);
                omcBillAdjustFee = omcBillAdjustFeeMapper.selectOne(omcBillAdjustFee);
                if (omcBillAdjustFee != null) {
                    map.put("beforeAdjustBalance", omcBillAdjustFee.getBeforeAdjustBalance());
                    map.put("afterAdjustBalance", omcBillAdjustFee.getAfterAdjustBalance());
                    map.put("totalFee", omcBillAdjustFee.getTotalFee());
                }
                break;
            case Constant.BILL_TYPE_CYCLE :  // 入院账单详情
                // TODO ???
                omcOldManBillDetailVo = queryBillDetail(omcOldManBillDto);   // 使用之前的接口
                map.put("omcOldManBillDetailVo", omcOldManBillDetailVo);
                break;
            default:
                log.warn("未知的缴费单类型");
        }

        return map;
    }

    @Override
    public Integer approveByAdmin(Long billId, Integer isPassed, LoginAuthDto loginAuthDto) {

        //查询缴费单
        OmcOldManBill oldManBill = selectByKey(billId);

        //获取用户角色
        List<RpcRoleVo> rpcRoleVos = uacRpcService.queryRoleListByUserId(loginAuthDto.getUserId());
        List<String> roleCodeList = rpcRoleVos.stream().map(r -> r.getRoleCode()).collect(Collectors.toList());
        if(!roleCodeList.contains("home") || !oldManBill.getGroupId().equals(loginAuthDto.getGroupId())){
            throw new OmcBizException(ErrorCodeEnum.OMC10037044);
        }
        //设置审批状态
        oldManBill.setIsPassed(isPassed);
        int ret = update(oldManBill);

        //创建推送请求对象 老人缴费单审批通过
        SendMessageRequest sendMessageRequest = new SendMessageRequest();
        sendMessageRequest.setGroupId(loginAuthDto.getGroupId());

        Oldman oldmanQuery = new Oldman();
        oldmanQuery.setOldmanId(oldManBill.getOldManId().intValue());
        oldmanQuery = oldmanService.selectByOld(oldmanQuery);
        //1-通过 0-拒绝 如果通过 设置老人状态为待缴费
        if(isPassed == 1){
            oldmanQuery.setStatus(Constant.DAIJIAOFEI);
            sendMessageRequest.setMsgCode(OldInConstant.IN_FLOW_OTHER_PEOPLE_BILL_AGREE);
        }else{
            //如果审批被拒绝 将老人状态设置为已评估，老人将回到接待部生成缴费单的待办事项
            oldmanQuery.setStatus(Constant.YIPINGGU);
            sendMessageRequest.setMsgCode(OldInConstant.IN_FLOW_OTHER_PEOPLE_BILL_REFUSE);
        }
        int retOldman = oldmanService.updateByOldId(oldmanQuery);

        opcMessageService.pushWithMsgCode(sendMessageRequest);

        return ret;
    }

    @Override
    public List<OmcOldManBillVo> queryNeedApproveListWithPage(OmcOldManBillDto omcOldManBillDto) {
        return omcOldManBillMapper.queryNeedApproveListWithPage(omcOldManBillDto);
    }

    /**
     * 根据账单Id查询该账单手动输入价格收费项列表
     *
     * @param billId the bill id
     * @return the list.
     */
    @Override
    public List<OmcBillItem> queryFixedListByBillId(Long billId) {

        OmcBillItem omcBillItem = new OmcBillItem();
        omcBillItem.setBillId(billId);
        omcBillItem.setIsFixedPrice(0); // 不固定价格 手动输入

        return omcBillItemService.select(omcBillItem);
    }

    /**
     * 确认周期账单
     *
     * @param confirmCycleBillDto
     *
     * @return
     */
    @Override
    public Integer confirmCycleBill(ConfirmCycleBillDto confirmCycleBillDto) {

        Long billId = confirmCycleBillDto.getBillId();

        // list 转 map
        List<OmcBillItem> list = confirmCycleBillDto.getOmcBillItemList();

        // 判断账单是否确认
        OmcOldManBill omcOldManBill = omcOldManBillMapper.selectByPrimaryKey(billId);
        if (PublicUtil.isEmpty(omcOldManBill)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10037049);
        }

        // 判断账单是否确认
        if (omcOldManBill.getIsConfirm().equals(1)) {
            throw new OmcBizException(ErrorCodeEnum.OMC10037050);
        }

        // 确认账单
        OmcBillItem omcBillItem = new OmcBillItem();
        omcBillItem.setBillId(billId);
        omcBillItem.setIsFixedPrice(0); // 不固定价格 手动输入

        List<OmcBillItem> omcBillItemList = omcBillItemService.select(omcBillItem);
        BigDecimal total = BigDecimal.ZERO;
        if (PublicUtil.isNotEmpty(omcBillItemList)) {
            if (PublicUtil.isEmpty(list)) {
                throw new OmcBizException(ErrorCodeEnum.OMC10037051);
            }

            if (list.size() != omcBillItemList.size()) {
                throw new OmcBizException(ErrorCodeEnum.OMC10037052);
            }

            Map<Long, OmcBillItem> map = Maps.newHashMap();
            map = list.stream().collect(Collectors.toMap(OmcBillItem::getId, item -> item));
            for (OmcBillItem item : omcBillItemList) {
                item.setActualFee(map.get(item.getId()).getActualFee());    // 缴费金额
                item.setRemark(map.get(item.getId()).getRemark());
                omcBillItemService.update(item);

                total = total.add(item.getActualFee());
            }
        }


        if (total.compareTo(BigDecimal.ZERO) > 0) {

            // 账单金额发生变化
            OmcBillPeriodFee omcBillPeriodFee = new OmcBillPeriodFee();
            omcBillPeriodFee.setBillId(billId);
            omcBillPeriodFee = omcBillPeriodFeeMapper.selectOne(omcBillPeriodFee);

            BigDecimal totalFee = omcBillPeriodFee.getTotalFee();
            totalFee = totalFee.add(total);

            BigDecimal after = omcBillPeriodFee.getAfterProduceBalance();   // 余额
            after = after.subtract(total);  // 余额 = 余额 - 缴费金额
            if (after.compareTo(BigDecimal.ZERO) < 0) { // 余额不够
                after = BigDecimal.ZERO;    // 余额为0
                totalFee = totalFee.subtract(after);
            }
            omcBillPeriodFee.setAfterProduceBalance(after);
            omcBillPeriodFee.setTotalFee(totalFee);

            BigDecimal theWeekPayFee = omcBillPeriodFee.getTheWeekPayFee(); // 本周缴费金额
            theWeekPayFee = theWeekPayFee.add(total);
            omcBillPeriodFee.setTheWeekPayFee(theWeekPayFee);


            BigDecimal advancePayFee = omcOldManBill.getAdvancePayFee();
            advancePayFee = advancePayFee.add(total);
            omcOldManBill.setAdvancePayFee(advancePayFee);
            omcOldManBill.setTotalPay(totalFee);

            omcBillPeriodFeeMapper.updateByPrimaryKeySelective(omcBillPeriodFee);
        }

        omcOldManBill.setIsConfirm(1);   // 周期账单已确认

        return omcOldManBillMapper.updateByPrimaryKeySelective(omcOldManBill);
    }

    /**
     * query fixed list by olmdan id list and date
     *
     * @param oldmanFixedQueryDto
     * @return
     */
    @Override
    public List<OldmanBillVo> queryFixedListByOldmanIdListAndDate(OldmanFixedQueryDto oldmanFixedQueryDto) {

        // 根据日期和机构查询当前账单日
        OmcPaymentCycle omcPaymentCycle = new OmcPaymentCycle();
        omcPaymentCycle.setGroupId(oldmanFixedQueryDto.getGroupId());
        omcPaymentCycle = paymentCycleService.selectOne(omcPaymentCycle);
        if (omcPaymentCycle == null) {
            throw new OmcBizException(ErrorCodeEnum.OMC10037054);
        }

        List<Date> dateList = CronUtil.getNextExecTimeOfMonthWithDate(omcPaymentCycle.getPaymentRecordGenerateConfig(),
                com.csun.cmny.util.DateUtil.stringToDate(oldmanFixedQueryDto.getDate()));
        // 账单日
        String date = com.csun.cmny.util.DateUtil.getDateStr(dateList.get(0));
        oldmanFixedQueryDto.setDate(date);

        return omcOldManBillMapper.queryFixedListByOldmanIdListAndDate(oldmanFixedQueryDto);
    }

    /**
     * 生成账单
     *
     * @param cycleBillDto
     * @return
     */
    @Override
    public Integer createCycleBillWithGroupId(CycleBillDto cycleBillDto) {

//        OmcPaymentCycle omcPaymentCycle = new OmcPaymentCycle();
//        omcPaymentCycle.setGroupId(cycleBillDto.getGroupId());
//        omcPaymentCycle = paymentCycleService.selectOne(omcPaymentCycle);
//        if (omcPaymentCycle == null) {
//            throw new OmcBizException(ErrorCodeEnum.OMC10037054);
//        }
//        List<Date> dateList = CronUtil.getNextExecTimeOfMonthWithDate(omcPaymentCycle.getPaymentRecordGenerateConfig(),
//                com.csun.cmny.util.DateUtil.stringToDate(cycleBillDto.getCycleDate()));
        // 3、查询机构所有的生成账单的老人
        OldmanInQueryDto oldmanInQueryDto = new OldmanInQueryDto();
        oldmanInQueryDto.setGroupId(cycleBillDto.getGroupId());
        List<Integer> statusList = Lists.newArrayList();
        statusList.add(Constant.YIRUYUAN);
        statusList.add(Constant.SHIRUZHU);
        oldmanInQueryDto.setStatusList(statusList);
        List<OldmanRpcVo> oldmanRpcVoList = oldmanService.queryOldmanByGroupIdAndStatusList(oldmanInQueryDto);

        for (OldmanRpcVo o : oldmanRpcVoList) {
            // 4、生成账单
            CycleBillDto dto = new CycleBillDto();
            dto.setCycleDate(com.csun.cmny.util.DateUtil.dateToStr(cycleBillDto.getCreateTime()));
            // dto.setCreateTime(dateList.get(0));
            dto.setOldmanId(o.getOldmanId());
            dto.setOldmanId(o.getOldmanId());
            dto.setInDate(cycleBillDto.getInDate());
            LoginAuthDto loginAuthDto = new LoginAuthDto();
            loginAuthDto.setGroupId(cycleBillDto.getGroupId());

            omcOldManBillService.createCycleBill(dto, loginAuthDto);

            log.info("cycleBillDto ==> {}, loginAuthDto ==> {}", cycleBillDto, loginAuthDto);
        }

        return null;
    }

    /**
     * 给一个默认的创建人--现在用于周期账单生成
     *
     * @return
     */
    public LoginAuthDto getLoginAuthDto() {
        if (null == this.loginAuthDto) {
            this.loginAuthDto = new LoginAuthDto();
            this.loginAuthDto.setUserId(1L);
            this.loginAuthDto.setUserName("周期账单");
        }
        return this.loginAuthDto;
    }


    public boolean checkOldmanInBillExist(Long oldmanId) {
        Example example = new Example(OmcOldManBill.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("oldManId", oldmanId);

        //缴费单类型 1-入院缴费单
        criteria.andEqualTo("billType", 1);

        //支付状态 1-支付
        criteria.andEqualTo("isPay", 0);
        if (selectCountByExample(example) > 0) {
            return true;
        } else {
            return false;
        }
    }

    public Integer moveInHospitalBill(OmcOldManBill oldManBill, List<OmcBillItem> billItemList, OmcBillMeal omcBillMeal, OmcBillInHospitalFee billInHospitalFee, LoginAuthDto loginAuthDto) {

        //判断是否已经生成了未缴费的入院账单
//        if (checkOldmanInBillExist(oldManBill.getOldManId())) {

        //查询原有缴费单
        OmcOldManBill deleteBill = new OmcOldManBill();
        deleteBill.setOldManId(oldManBill.getOldManId());
        deleteBill.setBillType(1);
        deleteBill = selectOne(deleteBill);
        if (deleteBill != null) {


//            delete(deleteBill);

            //定义账单id
            Long deleteBillId = deleteBill.getId();

            //删除原来的的账单数据

            //1.删除账单项目
            OmcBillItem billItemDel = new OmcBillItem();
            billItemDel.setBillId(deleteBillId);
            int retDelBillItem = omcBillItemService.delete(billItemDel);

            //2.删除绑定的套餐
//            OmcBillMeal billMeal = new OmcBillMeal();
//            billMeal.setBillId(billId);
//            int retDelBillMeal = omcBillMealService.delete(billMeal);

            //3.删除绑定的套餐项目
//            OmcBillSetMealItem billSetMealItem = new OmcBillSetMealItem();
//            billSetMealItem.setBillId(deleteBillId);
//            int retDelSetMealItem = omcBillSetMealItemService.delete(billSetMealItem);

            //4.删除账单绑定费用
            OmcBillInHospitalFee billInHospitalFeeDel = new OmcBillInHospitalFee();
            billInHospitalFeeDel.setBillId(deleteBillId);
            int retDelInHospitalFee = omcBillInHospitalFeeService.delete(billInHospitalFeeDel);

            //5.删除账单
            int retDeleteBill = deleteByKey(deleteBillId);
//        }
        }
        Long groupId = loginAuthDto.getGroupId();
        oldManBill.setBillNumber(DateUtil.getPayNumber(groupId));//账单号
        oldManBill.setBillType(1);//账单类型 1.入院账单 2.出院账单 3.调整账单 4.周期账单
        oldManBill.setIsPay(1);
        oldManBill.setUpdateInfo(loginAuthDto);
        oldManBill.setGroupId(groupId);
        int n = omcOldManBillMapper.insertSelective(oldManBill);//生成订单基础信息
        if (n > 0) {
            Long billId = oldManBill.getId();//账单ID
            //插入缴费项目信息
            if (null != billItemList && billItemList.size() > 0) {
                OmcBillItem billItemDto = new OmcBillItem();
                billItemDto.setGroupId(groupId);
                billItemDto.setBillId(billId);
                for (OmcBillItem billItem : billItemList) {//填充账单ID及机构ID信息
                    billItem.setGroupId(groupId);
                    billItem.setBillId(billId);
                    billItem.setUpdateInfo(loginAuthDto);
                }
                omcBillItemService.batchSave(billItemList);
            }
            //插入套餐信息
            if (null != omcBillMeal.getSetMealId()) {
                omcBillMeal.setGroupId(groupId);
                omcBillMeal.setBillId(billId);
                omcBillMeal.setUpdateInfo(loginAuthDto);
//                if (omcBillMealMapper.selectCount(billMealDto) > 0) {//该账单已有的套餐信息记录删除,避免干扰
//                    omcBillMealMapper.delete(billMealDto);
//                }
                int ret = omcBillMealService.save(omcBillMeal);

                if (omcBillMeal.getBillSetMealItemList() != null && omcBillMeal.getBillSetMealItemList().size() > 0) {
                    List<OmcBillSetMealItem> itemList = omcBillMeal.getBillSetMealItemList();
                    for (OmcBillSetMealItem item : itemList) {
                        item.setGroupId(groupId);
                        item.setBillId(billId);
                        item.setUpdateInfo(loginAuthDto);
                    }
                    int retBatchInsert = omcBillSetMealItemService.batchSave(itemList);
                }
            }
            //插入入院账单费用统计
            billInHospitalFee.setGroupId(groupId);
            billInHospitalFee.setBillId(billId);
            billInHospitalFee.setUpdateInfo(loginAuthDto);
            omcBillInHospitalFeeMapper.insertSelective(billInHospitalFee);
            return 1;
        } else {
            return 0;
        }
    }
    /*
     * 集团化缴费记录单查询
     * */
    @Override
    public List<OldmanBillInforVo> selectAllBill(OldmanBillInforVo oldmanbill) {
        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryGroupListByGroupId(oldmanbill.getGroupId());
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }
        List<OldmanBillInforVo> oldmanBillInforVos = omcOldManBillMapper.selectAllBill(oldmanbill,groupIdList);
        for (OldmanBillInforVo o:oldmanBillInforVos) {
            for (GroupVo g:groupVoList) {
                if(g.getId().equals(o.getGroupId().longValue())){
                    o.setGroupName(g.getGroupName());
                }
            }
        }
        return oldmanBillInforVos;
    }
    /*
     * 营业额报表查询
     * */
    @Override
    public List<TurnoverVo> selectTurnover(TurnoverVo turnoverVo) {
        /**
         * @date    2021-11-19
         * @author  chisj
         * @desc    获取子机构id集合
         */
        List<GroupVo> groupVoList = uacRpcService.queryGroupListByGroupId(turnoverVo.getGroupId());
        if (PublicUtil.isEmpty(groupVoList)) {
            return Lists.newArrayList();
        }

        List<Long> groupIdList = Lists.newArrayList();
        for (GroupVo gv : groupVoList) {
            groupIdList.add(gv.getId());
        }
        List<TurnoverVo> turnoverVos = omcOldManBillMapper.selectTurnover(turnoverVo,groupIdList);
        for (TurnoverVo t:turnoverVos) {
            for (GroupVo g:groupVoList) {
                if(t.getGroupId().equals(g.getId())){
                    t.setGroupName(g.getGroupName());
                }
            }
        }
        /*
        * 合计查询
        * */
        List<MonthToTurnoverVo> monthToTurnoverVos = omcOldManBillMapper.selectTurnoverByMonth(turnoverVo,groupIdList);

        TurnoverVo turnover = new TurnoverVo();
        turnover.setGroupName("合计");
        turnover.setMonths(monthToTurnoverVos);
        turnoverVos.add(turnover);
        return turnoverVos;
    }

}
